<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['quotation:pricing:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pricingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column label="客户名称" align="center" prop="clientName" :show-overflow-tooltip="true" />
      <el-table-column label="产品名称" align="center" prop="productsName" :show-overflow-tooltip="true" />
      <el-table-column label="产品规格" align="center" prop="productsSpecification" :show-overflow-tooltip="true" />
      <el-table-column label="未税单价" align="center" prop="wsPrice" />
      <el-table-column label="含税单价" align="center" prop="hsPrice" />
      <el-table-column label="税率" align="center" prop="rate">
        <template #default="scope">
          <span>{{ scope.row.rate ? (scope.row.rate * 100).toFixed(0) + '%' : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="利润率" align="center" prop="profitmargin">
        <template #default="scope">
          <span>{{ scope.row.profitmargin ? (scope.row.profitmargin * 100).toFixed(0) + '%' : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleAudit(scope.row)"
            v-hasPermi="['quotation:pricing:audit']"
            v-if="scope.row.status === '财务审核中'"
          >财务审核</el-button>
          <el-button
            link
            type="warning"
            icon="RefreshLeft"
            @click="handleReaudit(scope.row)"
            v-hasPermi="['quotation:pricing:reaudit']"
            v-if="scope.row.status === '总经理审核中'"
          >反审核</el-button>
          <el-button
            link
            type="primary"
            icon="View"
            @click="handleDetail(scope.row)"
            v-hasPermi="['quotation:pricing:query']"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 成本核算对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="pricingForm" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单编号" prop="orderNo">
              <el-input v-model="form.orderNo" placeholder="订单编号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="clientName">
              <el-input v-model="form.clientName" placeholder="客户名称" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productsName">
              <el-input v-model="form.productsName" placeholder="产品名称" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品规格" prop="productsSpecification">
              <el-input v-model="form.productsSpecification" placeholder="产品规格" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">成本核算内容</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="材料" prop="material">
              <el-input-number v-model="form.material" :precision="2" :step="0.1" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="挤压费" prop="extrusion">
              <el-input-number v-model="form.extrusion" :precision="2" :step="0.1" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="后加工费" prop="backend">
              <el-input-number v-model="form.backend" :precision="2" :step="0.1" controls-position="right" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="外协费" prop="outsourcing">
              <el-input-number v-model="form.outsourcing" :precision="2" :step="0.1" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="组装费" prop="assemble">
              <el-input-number v-model="form.assemble" :precision="2" :step="0.1" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检验费" prop="inspection">
              <el-input-number v-model="form.inspection" :precision="2" :step="0.1" controls-position="right" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="包装费" prop="wrap">
              <el-input-number v-model="form.wrap" :precision="2" :step="0.1" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运输费" prop="transport">
              <el-input-number v-model="form.transport" :precision="2" :step="0.1" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售费" prop="sale">
              <el-input-number v-model="form.sale" :precision="2" :step="0.1" controls-position="right" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="管理费" prop="manage">
              <el-input-number v-model="form.manage" :precision="2" :step="0.1" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="广告费" prop="ad">
              <el-input-number v-model="form.ad" :precision="2" :step="0.1" controls-position="right" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">价格计算</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="利润率" prop="profitmargin">
              <el-input-number v-model="form.profitmargin" :precision="2" :step="0.01" :min="0" :max="1" controls-position="right">
                <template #suffix>%</template>
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="税率" prop="rate">
              <el-input-number v-model="form.rate" :precision="2" :step="0.01" :min="0" :max="1" controls-position="right">
                <template #suffix>%</template>
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button type="primary" @click="handleCalculate">计算价格</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="未税单价" prop="wsPrice">
              <el-input-number v-model="form.wsPrice" :precision="2" :step="0.1" controls-position="right" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="含税单价" prop="hsPrice">
              <el-input-number v-model="form.hsPrice" :precision="2" :step="0.1" controls-position="right" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 详情对话框 -->
    <el-dialog title="成本核算详情" v-model="detailOpen" width="1000px" append-to-body>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="订单编号">{{ detailForm.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ detailForm.clientName }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ detailForm.productsName }}</el-descriptions-item>
        <el-descriptions-item label="产品规格">{{ detailForm.productsSpecification }}</el-descriptions-item>
        <el-descriptions-item label="材料费">{{ detailForm.material }}</el-descriptions-item>
        <el-descriptions-item label="挤压费">{{ detailForm.extrusion }}</el-descriptions-item>
        <el-descriptions-item label="后加工费">{{ detailForm.backend }}</el-descriptions-item>
        <el-descriptions-item label="外协费">{{ detailForm.outsourcing }}</el-descriptions-item>
        <el-descriptions-item label="组装费">{{ detailForm.assemble }}</el-descriptions-item>
        <el-descriptions-item label="检验费">{{ detailForm.inspection }}</el-descriptions-item>
        <el-descriptions-item label="包装费">{{ detailForm.wrap }}</el-descriptions-item>
        <el-descriptions-item label="运输费">{{ detailForm.transport }}</el-descriptions-item>
        <el-descriptions-item label="销售费">{{ detailForm.sale }}</el-descriptions-item>
        <el-descriptions-item label="管理费">{{ detailForm.manage }}</el-descriptions-item>
        <el-descriptions-item label="广告费">{{ detailForm.ad }}</el-descriptions-item>
        <el-descriptions-item label="利润率">{{ detailForm.profitmargin ? (detailForm.profitmargin * 100).toFixed(0) + '%' : '' }}</el-descriptions-item>
        <el-descriptions-item label="税率">{{ detailForm.rate ? (detailForm.rate * 100).toFixed(0) + '%' : '' }}</el-descriptions-item>
        <el-descriptions-item label="未税单价">{{ detailForm.wsPrice }}</el-descriptions-item>
        <el-descriptions-item label="含税单价">{{ detailForm.hsPrice }}</el-descriptions-item>
        <el-descriptions-item label="审核人">{{ detailForm.updateBy }}</el-descriptions-item>
        <el-descriptions-item label="审核时间">{{ detailForm.updateTime }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="3">{{ detailForm.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import { listPricing, getPricing, getPricingByOrderNo, updatePricing, auditPricing, reauditPricing, calculatePrice, exportPricing } from "@/api/quotation/pricing";

const { proxy } = getCurrentInstance();

// 遮罩层
const loading = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 成本核算表格数据
const pricingList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 是否显示详情弹出层
const detailOpen = ref(false);
// 是否为财务审核
const isAudit = ref(true);

// 状态数据字典
const statusOptions = ref([
  { label: '工程审核中', value: '工程审核中' },
  { label: '财务审核中', value: '财务审核中' },
  { label: '总经理审核中', value: '总经理审核中' },
  { label: '报价审核完成', value: '报价审核完成' },
  { label: '财务反审核完成', value: '财务反审核完成' }
]);

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  orderNo: undefined
});

// 表单参数
const form = ref({});

// 详情表单参数
const detailForm = ref({});

// 表单校验
const rules = ref({
  profitmargin: [{ required: true, message: "利润率不能为空", trigger: "blur" }],
  rate: [{ required: true, message: "税率不能为空", trigger: "blur" }],
});

/** 查询成本核算列表 */
function getList() {
  loading.value = true;
  listPricing(queryParams.value).then(response => {
    pricingList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    orderNo: undefined,
    clientName: undefined,
    productsName: undefined,
    productsSpecification: undefined,
    material: 0,
    extrusion: 0,
    backend: 0,
    outsourcing: 0,
    assemble: 0,
    inspection: 0,
    wrap: 0,
    transport: 0,
    sale: 0,
    manage: 0,
    ad: 0,
    rate: 0.13,
    profitmargin: 0.3,
    wsPrice: 0,
    hsPrice: 0,
    remark: undefined
  };
  proxy.resetForm("pricingForm");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 财务审核按钮操作 */
function handleAudit(row) {
  reset();
  isAudit.value = true;
  
  // 获取报价单详情和成本核算信息
  getPricingByOrderNo(row.orderNo).then(response => {
    if (response.data) {
      // 存在成本核算信息，直接使用
      form.value = response.data;
    } else {
      // 不存在成本核算信息，设置默认值
      form.value.orderNo = row.orderNo;
      form.value.clientName = row.clientName;
      form.value.productsName = row.productsName;
      form.value.productsSpecification = row.productsSpecification;
    }
    
    open.value = true;
    title.value = "财务审核";
  });
}

/** 财务反审核按钮操作 */
function handleReaudit(row) {
  reset();
  isAudit.value = false;
  
  // 获取成本核算信息
  getPricingByOrderNo(row.orderNo).then(response => {
    if (response.data) {
      form.value = response.data;
      open.value = true;
      title.value = "财务反审核";
    } else {
      proxy.$modal.msgError("未找到成本核算信息");
    }
  });
}

/** 详情按钮操作 */
function handleDetail(row) {
  getPricingByOrderNo(row.orderNo).then(response => {
    detailForm.value = response.data;
    detailForm.value = {
      ...detailForm.value,
      clientName: row.clientName,
      productsName: row.productsName,
      productsSpecification: row.productsSpecification
    };
    detailOpen.value = true;
  });
}

/** 计算价格 */
function handleCalculate() {
  calculatePrice(form.value).then(response => {
    form.value.wsPrice = response.data.wsPrice;
    form.value.hsPrice = response.data.hsPrice;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["pricingForm"].validate(valid => {
    if (valid) {
      if (isAudit.value) {
        // 执行财务审核
        auditPricing(form.value).then(response => {
          proxy.$modal.msgSuccess("财务审核成功");
          open.value = false;
          getList();
        });
      } else {
        // 执行财务反审核
        reauditPricing(form.value).then(response => {
          proxy.$modal.msgSuccess("财务反审核成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('/quotation/pricing/export', {
    ...queryParams.value
  }, `pricing_${new Date().getTime()}.xlsx`);
}

onMounted(() => {
  getList();
});
</script> 